<?php

/**
 *    支付宝支付方式插件
 *
 *    @author    Garbin
 *    @usage    none
 */
class EpayalipayPayment extends BasePayment {

    /**
     *    获取支付表单
     *
     *    @author    Garbin
     *    @param     array $order_info  待支付的订单信息，必须包含总费用及唯一外部交易号
     *    @return    array
     */
    function get_payform($order_info) {
        $order_info=$this->get_order_info($order_info);
        
        if(!$order_info){
            return false;
        }
        $alipay_config['sign_type'] = strtoupper('MD5');
        $alipay_config['input_charset'] = strtolower('utf-8');
        $alipay_config['cacert'] = ROOT_PATH.'/includes/payments/epayalipay/lib' . '\\cacert.pem';
        $alipay_config['transport'] = 'http';
        $alipay_config['partner'] = Conf::get('payment_alipay_partner');
        $alipay_config['key'] = Conf::get('payment_alipay_key');

        require_once(ROOT_PATH."/includes/payments/epayalipay/lib/alipay_submit.class.php");

//构造要请求的参数数组，无需改动
        $parameter = array(
            "service" => "create_direct_pay_by_user",
            "partner" => trim($alipay_config['partner']),
            "payment_type" => '1',
            "notify_url" => $this->_create_notify_url($order_info['order_id']),
            "return_url" => $this->_create_return_url($order_info['order_id']),
            "seller_email" => Conf::get('payment_alipay_seller_email'),
            "out_trade_no" => $order_info['order_sn'],
            "subject" => $this->_get_subject($order_info),
            "total_fee" => $order_info['money'],
            "body" => $this->_get_subject($order_info),
            "show_url" => site_url() . "/index.php?app=account_log&act=czlist",
            "anti_phishing_key" => "",
            "exter_invoke_ip" => "",
            "_input_charset" => trim(strtolower($alipay_config['input_charset']))
        );
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认");
        header("Content-type: text/html; charset=utf-8"); 
        echo $html_text;exit;
    }

    function _create_return_url($order_id)
    {
        return site_url() . "/index.php?app=buyer_order";
    }
            
    function _create_notify_url($order_id) {
        return site_url() . "/notifyalipay.php";
    }

    /**
     *    返回通知结果
     *
     *    @author    Garbin
     *    @param     array $order_info
     *    @param     bool  $strict
     *    @return    array
     */
    function verify_notify() {
        $alipay_config['sign_type'] = strtoupper('MD5');
        $alipay_config['input_charset'] = strtolower('utf-8');
        $alipay_config['cacert'] = ROOT_PATH.'/includes/payments/epayalipay/lib' . '\\cacert.pem';
        $alipay_config['transport'] = 'http';
        $alipay_config['partner'] = Conf::get('payment_alipay_partner');
        $alipay_config['key'] = Conf::get('payment_alipay_key');

        require_once(ROOT_PATH."/includes/payments/epayalipay/lib/alipay_notify.class.php");

        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();

        if ($verify_result) {//验证成功
            if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                //验证成功，返回支付所需的订单信息
                $notify_result = array(
                    'out_trade_no' => $_POST['out_trade_no'], #商户订单号
                    'trade_no' => $_POST['trade_no'], #交易凭据单号
                    'total_fee' => $_POST['total_fee'], #涉及金额
                    'trade_status' => '1',
                );
            } else {
                $notify_result = array(
                    'trade_status' => '0',
                );
            }
        } else {

            $notify_result = array(
                'trade_status' => '0',
            );
        }
        return $notify_result;
    }

    function verify_return($order_info, $strict = false) {
        $alipay_config['sign_type'] = strtoupper('MD5');
        $alipay_config['input_charset'] = strtolower('utf-8');
//        $alipay_config['cacert'] = getcwd() . '\\cacert.pem';
        $alipay_config['cacert'] =ROOT_PATH. '/includes/payments/epayalipay/lib' . '\\cacert.pem';
        $alipay_config['transport'] = 'http';
        $alipay_config['partner'] = Conf::get('payment_alipay_partner');
        $alipay_config['key'] = Conf::get('payment_alipay_key');



        require_once(ROOT_PATH."/includes/payments/epayalipay/lib/alipay_notify.class.php");

        if (empty($order_info)) {
            $this->_error('order_info_empty');
            return false;
        }

        $out_trade_no = $_GET['out_trade_no'];
        $trade_no = $_GET['trade_no'];
        $total_fee = $_GET['total_fee'];

        if ($order_info['order_sn'] != $out_trade_no) {
            /* 通知中的订单与欲改变的订单不一致 */
            $this->_error('order_inconsistent');
            return false;
        }
        if (bcsub($order_info['order_amount'] , $order_info['pd_amount'],2) != $total_fee) {
            /* 支付的金额与实际金额不一致 */
            $this->_error('price_inconsistent');
            return false;
        }


        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyReturn();

        if ($verify_result) {
            if ($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
                if ($order_info['status'] == ORDER_PENDING) {
                    /* 如果是等待付款中，则说明是即时到账交易，这时将状态改为已付款 */
                    $order_status = ORDER_ACCEPTED;
                }
            }


            switch ($_GET['trade_status']) {
                case 'WAIT_SELLER_SEND_GOODS':      //买家已付款，等待卖家发货

                    $order_status = ORDER_ACCEPTED;
                    break;

                case 'WAIT_BUYER_CONFIRM_GOODS':    //卖家已发货，等待买家确认

                    $order_status = ORDER_SHIPPED;
                    break;

                case 'TRADE_FINISHED':              //交易结束
                case 'TRADE_SUCCESS':               // 交易成功
                    if ($order_info['status'] == ORDER_PENDING) {
                        /* 如果是等待付款中，则说明是即时到账交易，这时将状态改为已付款 */
                        $order_status = ORDER_ACCEPTED;
                    } else {
                        /* 说明是第三方担保交易，交易结束 */
                        $order_status = ORDER_FINISHED;
                    }
                    break;
                case 'TRADE_CLOSED':                //交易关闭
                    $order_status = ORDER_CANCLED;
                    break;

                default:
                    $this->_error('undefined_status');
                    return false;
                    break;
            }
            return array(
                'target' => $order_status,
            );
        } else {
            /* 若本地签名与网关签名不一致，说明签名不可信 */
            $this->_error('sign_inconsistent');
            return false;
        }
    }

}

?>